import React, { useState, useEffect } from 'react';
import { Form, Select, Table, Button, Alert } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';
import { ruleApi } from '../../services/api';

const { Option } = Select;

interface TableSelectStepProps {
  form: FormInstance;
}

const TableSelectStep: React.FC<TableSelectStepProps> = ({ form }) => {
  const [availableTables, setAvailableTables] = useState<any[]>([]);
  const [tableFields, setTableFields] = useState<Record<string, any[]>>({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchTableList();
  }, []);

  const fetchTableList = async () => {
    try {
      setLoading(true);
      const response = await ruleApi.getTableList();
      setAvailableTables(response.data.data);
    } catch (error) {
      console.error('获取数据表列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchTableFields = async (tableName: string) => {
    try {
      const response = await ruleApi.getTableFields(tableName);
      setTableFields(prev => ({
        ...prev,
        [tableName]: response.data.data,
      }));
    } catch (error) {
      console.error('获取表字段信息失败:', error);
    }
  };

  const handleTableSelect = (tableName: string) => {
    const currentTables = form.getFieldValue('tables') || [];
    if (!currentTables.includes(tableName)) {
      form.setFieldValue('tables', [...currentTables, tableName]);
      fetchTableFields(tableName);
    }
  };

  const handleTableRemove = (tableName: string) => {
    const currentTables = form.getFieldValue('tables') || [];
    const newTables = currentTables.filter((table: string) => table !== tableName);
    form.setFieldValue('tables', newTables);
    
    // 清理相关配置
    const currentJoins = form.getFieldValue('joins') || [];
    const newJoins = currentJoins.filter(
      (join: any) => join.leftTable !== tableName && join.rightTable !== tableName
    );
    form.setFieldValue('joins', newJoins);
  };

  const selectedTables = form.getFieldValue('tables') || [];

  const columns = [
    {
      title: '表名',
      dataIndex: 'tableName',
      key: 'tableName',
    },
    {
      title: '表描述',
      dataIndex: 'tableComment',
      key: 'tableComment',
    },
    {
      title: '字段数',
      dataIndex: 'fieldCount',
      key: 'fieldCount',
      render: (_: any, record: any) => {
        const fields = tableFields[record.tableName] || [];
        return fields.length;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleTableRemove(record.tableName)}
        >
          移除
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Alert
        message="选择数据表"
        description="请选择需要统计的数据表，支持多表关联查询。选择后系统会自动加载表字段信息。"
        type="info"
        style={{ marginBottom: 16 }}
      />

      <Form.Item
        name="tables"
        label="已选择的数据表"
        rules={[{ required: true, message: '请至少选择一个数据表' }]}
      >
        <Select
          mode="multiple"
          placeholder="请选择数据表"
          loading={loading}
          onSelect={handleTableSelect}
          style={{ width: '100%' }}
        >
          {availableTables.map((table: any) => (
            <Option key={table.tableName} value={table.tableName}>
              {table.tableName} ({table.tableComment})
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Table
        columns={columns}
        dataSource={availableTables.filter(table => selectedTables.includes(table.tableName))}
        rowKey="tableName"
        pagination={false}
        style={{ marginTop: 16 }}
      />

      {selectedTables.length > 1 && (
        <div style={{ marginTop: 16 }}>
          <h4>表关联配置</h4>
          <p style={{ color: '#666' }}>当选择多个数据表时，需要配置表之间的关联关系</p>
          {/* TODO: 实现表关联配置 */}
        </div>
      )}
    </div>
  );
};

export default TableSelectStep;